var express = require('express');
var router = express.Router()
let User=require("../models/user");
let config = require("../config");
let Category = require("../models/category");
let Blog =require("../models/blog");
let Favorites =require("../models/favorites");
let Links = require('../models/links')

router.use(function(req, res, next) {
    if (!req.user.isAdmin) {
        //非管理员用户
        res.send('对不起，只有管理员才可进入后台管理')
        return
    }
    next()
})

// define the home page route
router.get('/', function (req, res) {
    res.render('./admin/index',{user:req.user})

})
// define the about route
router.get('/user',  async function (req, res) {
    //判断page存在 及范围
    let maxItem = config.pageSetting.MaxItem;
    let count = await  User.find({}).countDocuments();
    let maxPage = await Math.max(Math.ceil(count/maxItem),1);
    let page = Math.min(Math.max( req.query.page,1),maxPage);
    let users = await User.find({}).limit(maxItem).skip((page-1)*maxItem);
    res.render('./admin/user_index',{
        userInfo:req.user,
        users:users,
        page:page,
        maxPage:maxPage,
    })
})
router.get('/user/delete',async function (req,res){
    let id = req.query.id;
      await  User.deleteOne({_id:id},function (err){})
    res.render('./admin/Jump_index',{
        msg:'修改成功',
        url:'/admin/user?page=1'
    })
})
router.get('/user/change',async function (req,res){
    let id =req.query.id;
    let userByUser = await User.findById(id);
    res.render('./admin/user_change',{
        user:userByUser,
        msg:'修改用户信息'
    })
})
router.post('/user/change',async function (req,res){
    let id = req.body.userId;
    let name = req.body.name;
    let psw = req.body.psw;
    await User.updateOne({_id:id},{userName:name,passWord:psw});
    res.send({
        msg:'修改成功'
    })
})
//获取博客分类管理界面
router.get('/category', async function (req,res){
    let maxItem = config.pageSetting.MaxItem;
    let count = await  Category.find({}).countDocuments();
    let maxPage = await Math.max( Math.ceil(count/maxItem),1);
    let page = Math.min(Math.max( req.query.page,1),maxPage);
    let categorys = await Category.find({}).limit(maxItem).skip((page-1)*maxItem);
    res.render('./admin/category_index',{
        msg:"新建分类",
        categorys:categorys,
        page:page,
        maxPage:maxPage,
    })
})
//分类更改
router.get('/category/change',async function (req,res){
    let id= req.query.id
    let category= await Category.findById(id,function (err){
        if(err){
            console.log(err)
        }
    })
    res.render("./admin/category_change",{
        category:category,
    })
})

router.post("/category/change",async function(req,res){
    let id = req.body.categoryId;
    let name =req.body.name;
    Category.updateOne({_id:id},{name:name},function (err){
        if(err){
            console.log(err);
        }
    })
    res.send({msg:"修改成功"})
})

//分类删除
router.get('/category/delete', async function (req,res){
    let id = req.query.id;
   let idFromDb = await  Category.findOne({_id:id},function (err){
      if(err){
          console.log(err);
      }
   });
    if(!idFromDb){
        res.render('./admin/Jump_index',{msg:'未找到该id',
        url:"/admin/category?page=1"})
    }else {
         Category.deleteOne({_id:id},function (err){
             if(err){
                 console.log(err);
             }
         });
        res.render('./admin/Jump_index',{msg:'success',
            url:"/admin/category?page=1"})
    }
})
router.get('/category/add',function (req,res){
    res.render('./admin/category_add');
})
//分类的增加
router.post('/category/add', async function (req,res){
    let name = req.body.name.toString();
    let articleNumber = req.body.articleNumber;
    const nameFormDb =await Category.findOne({name:name});
    if(nameFormDb){
        res.send({'msg':'failure'})
    }else {
        new Category({name:name,articleNumber:articleNumber}).save();
        res.send({'msg':'success'})
    }
})
//博客增加界面
router.get('/blog/add',async function (req,res){
    let categorys = await Category.find({});
    res.render('./admin/blog_add',{msg:"success",
    categorys:categorys});
})
//博客增加和修改
router.post('/blog/add',async function (req,res){
    let category = req.body.category.toString();
     let title = req.body.title.toString();
     let author = req.body.author.toString();
     let synopsis =req.body.synopsis.toString();
     let content =req.body.content.toString();
     let blogId =req.body.blogId;
     //修改博客
     if(blogId!=""){
         Blog.updateOne({_id:blogId},{category:category,title:title,author:author,synopsis:synopsis,
             content:content},function (err){
             if(err){
                 console.log(err)
             }
         })
         res.send({msg:"修改成功"})
     }else//增加博客
     {
     const TitleFormBlog =await Blog.findOne({title:title});
     if(TitleFormBlog){
         res.send({msg:"该文章已存在"})
     }else {
         new Blog ({category:category,title:title,author:author,synopsis:synopsis,
             content:content,reading:0}).save();
         let temp = await Category.findOne({name:category});
         let articleNumber= (temp.articleNumber) +1;
         await Category.updateOne({name:category},{articleNumber:articleNumber})
         res.send({
                 msg: "保存成功",
             }
         );
     }}
})
//博客管理界面
router.get('/blog', async function (req,res){
    let maxItem = config.pageSetting.MaxItem;
    let count = await Blog.find({}).countDocuments();
    let maxPage =await Math.max(Math.ceil( count/maxItem),1);
    let page = Math.min(Math.max( req.query.page,1),maxPage);

    let blogs = await Blog.find({}).limit(maxItem).skip((page-1)*maxItem);
    res.render('./admin/blog_handler',{
        blogs:blogs,
        page:page,
        maxPage:maxPage,
    })

})
//博客删除
router.get('/blog/delete',async function (req,res){
             let id= req.query.id;
             let idFromBlog = await Blog.findById(id);
             await Blog.deleteOne({_id:id});
             let temp =await Category.findOne({name:idFromBlog.category});
             let articleNumber = (temp.articleNumber)-1;
             console.log(articleNumber)
             await  Category.updateOne({name:idFromBlog.category},{articleNumber:articleNumber},function (err){

            });
             res.render("./admin/Jump_index",
                 {msg:"删除成功",
                     url:'/admin/blog?page=1'});
})
//博客编辑
router.get('/blog/change',async function (req,res){
    let id = req.query.id;
    let blogFromId = await Blog.findById(id,function (err){
        if(err){
            console.log(err)
        }
    })
    res.render('admin/blog_add',{
        blog:blogFromId,
    })
})
//博客查看
router.get("/blog/detail",async function (req,res){
    let id =req.query.id;

})

//收藏夹
router.get('/favorites', async function (req,res){
    let maxItem = config.pageSetting.MaxItem;
    let count = await  Favorites.find({}).countDocuments();
    let maxPage = await Math.max( Math.ceil(count/maxItem),1);
    let page = Math.min(Math.max( req.query.page,1),maxPage);
    let blogId = await Favorites.find({}).limit(maxItem).skip((page-1)*maxItem);
    let blogs= new Array();
    await blogId.forEach(function (item,index){
          let temp = item.blogId;
          Blog.findById(temp,function (err,data){
              blogs.push(data)
          })
    });
    await res.render('./admin/blog_favorites',{
        msg:"添加至收藏夹",
        blogs:blogs,
        page:page,
        maxPage:maxPage,
    })
})

//友情链接
router.get('/links', async function (req,res){
    let maxItem = config.pageSetting.MaxItem;
   let count = await Links.find({}).countDocuments();
    let maxPage = await Math.max( Math.ceil(count/maxItem),1);
    let page = Math.min(Math.max( req.query.page,1),maxPage);
    let LinksItem = await Links.find({}).limit(maxItem).skip((page-1)*maxItem);
    res.render('./admin/links',{
        msg:"链接管理",
        links:LinksItem,
        page:page,
        maxPage:maxPage,
    })
})

router.get('/links/add',async function (req,res){
    res.render("./admin/links_add")
})
//链接页面的更改和添加
router.post('/links/add',async function (req,res){
    let name =req.body.name;
    let url =req.body.url;
    console.log(url);
    let id =req.body.id;
    if(id){
        Links.updateOne({_id:id},{name:name,url:url},function (err){})
        res.send({
            msg:'修改成功'
        })
    }else {
        new Links({name:name,url:url}).save()
        res.send({
            msg:'提交成功'
        })
    }
})
router.get('/links/change',async function (req,res){
    let id = req.query.id;
    let linkById =await Links.findById(id);
    res.render('./admin/links_add',{
        link:linkById,
    })
})
router.get('/links/delete',async function (req,res){
    let id =req.query.id;
    Links.deleteOne({_id:id},function (err){});
    res.render('./admin/Jump_index',{
        msg:'删除成功',
        url:'/admin/links?page=1'
    })
})



module.exports = router;